package com.chijun.mform.full.view;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.LinearLayout;

import androidx.annotation.Nullable;

import com.chijun.mform.FormBuilder;
import com.chijun.mform.R;
import com.chijun.mform.create.IWaitResult;
import com.chijun.mform.create.fragment.FormAddProcessFragment;
import com.chijun.mform.create.mode.FormApprovePerson;
import com.chijun.mform.create.mode.FormApproveProcess;
import com.chijun.mform.full.IHandleWriterData;
import com.chijun.mform.full.IResultFormConfig;
import com.chijun.mform.full.mode.ModeFormFile;
import com.chijun.mform.full.mode.ModeFormFullApprovePerson;
import com.chijun.mform.full.mode.ModeFormFullFileData;
import com.chijun.mform.full.mode.ModeFormOrdinaryFieldData;
import com.chijun.mform.full.mode.ModeFullForm;
import com.chijun.mform.full.mode.ModeLoadServerFormConfigData;
import com.chijun.mform.full.mode.ModeServerSubmitData;
import com.example.ccj.b.c.custom.MButton;
import com.example.ccj.b.c.dialog.ErrorDialog;
import com.example.ccj.b.c.dialog.LoadingDialog;
import com.example.ccj.u.GenerateId;
import com.example.ccj.u.LogUtils;
import com.example.ccj.u.SPUtils;
import com.example.ccj.u.StringUtils;
import com.example.ccj.u.TimeUtils;
import com.example.ccj.u.ToastUtils;
import com.example.ccj.u.sqlite.SqliteExcuteCommand;

import java.util.ArrayList;
import java.util.List;

/**
 * 加载表单数据
 * @author 驰珺
 * whechat   : chijun9
 * create at : 2024/12/9 22:53
 */
public class ViewLoadForm extends LinearLayout {

    ViewLoadFormField loadFormFieldView;        //表单的字段模块
    ViewLoadFormApprove loadFormApproveView;    //表单的审批模块
    ModeLoadServerFormConfigData writeFormData; //表单的所有相关数据
    IHandleWriterData iHandleWriterData;        //数据回调接口
    IWaitResult iWaitResult;                    //保存成功回调接口

    /**
     * 构造 传入表单id加载数据
     * @param context 上下文
     * @param formId 表单id
     * @param iHandleWriterData 需要连接服务器的一些接口
     * @param iWaitResult 表单保存完毕回调
     */
    @Deprecated
    public ViewLoadForm(Context context, String formId, IHandleWriterData iHandleWriterData, IWaitResult iWaitResult) {
        super(context);
        initDefData();
        setFormData(formId,iHandleWriterData,iWaitResult);
    }

    public ViewLoadForm(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initDefData();
    }

    private void initDefData() {

    }

    /**
     * 通过表单id获取表单数据
     * @param formId 表单id
     * @param iHandleWriterData 需要连接服务器的一些接口
     * @param iWaitResult 表单保存完毕回调
     */
    public void setFormData(String formId,IHandleWriterData iHandleWriterData,IWaitResult iWaitResult){
        this.iHandleWriterData = iHandleWriterData;
        this.iWaitResult = iWaitResult;
        LoadingDialog loadingDialog2 = new LoadingDialog(getContext());
        if (iHandleWriterData != null) {
            loadingDialog2.showLoading();
            //回调接口获取数据
            iHandleWriterData.getFormFullConfig(formId, new IResultFormConfig() {
                @Override
                public void result(String formConfig) {
                    writeFormData = ModeLoadServerFormConfigData.analysis(formConfig);
                    if (writeFormData != null) {
                        loadingDialog2.dismiss();
                        init();
                    } else {
                        loadingDialog2.dismiss();
                        ErrorDialog errorDialog = new ErrorDialog(getContext(),"表单数据解析失败！");
                        errorDialog.show();
                    }
                }

                @Override
                public void onError(String errorStr) {
                    ErrorDialog errorDialog = new ErrorDialog(getContext(),errorStr);
                    errorDialog.show();
                    loadingDialog2.dismiss();
                }
            });
        } else {
            LogUtils.e("未传入必须参数回调 iHandleWriterData");
        }
    }

    /**
     * 传入表单数据加载表单
     * @param writeFormData 获取到的数据
     * @param iHandleWriterData 需要连接服务器的一些接口
     * @param iWaitResult   表单保存完毕回调
     */
    @Deprecated
    public void setFormData(ModeLoadServerFormConfigData writeFormData, IHandleWriterData iHandleWriterData, IWaitResult iWaitResult){
        this.writeFormData = writeFormData;
        this.iHandleWriterData = iHandleWriterData;
        this.iWaitResult = iWaitResult;
        init();
    }

    private void init(){
        LinearLayout.inflate(getContext(), R.layout.view_load_form,this);
        loadFormFieldView = findViewById(R.id.view_load_form_filed_view);
        loadFormApproveView = findViewById(R.id.view_load_form_approve_view);
        MButton zanCun = findViewById(R.id.view_load_form_zan_cun);
        MButton submit = findViewById(R.id.view_load_form_submit);

        zanCun.setOnClickListener(v -> zanCun());
        submit.setOnClickListener(v -> submit());

        loadFormFieldView.setiHandleWriterData(iHandleWriterData);
        loadFormFieldView.setFormData(writeFormData);
        if (writeFormData.form.type == 1) loadFormApproveView.setFormData(writeFormData);
    }

    /**
     * 获取提交表单数据
     */
    public void submit(){
        LoadingDialog loadingDialog = new LoadingDialog(getContext());
        loadingDialog.showLoading();

        ModeServerSubmitData submitData = handlerServerData();
        if (submitData != null) {
            //添加提交人
            ModeFormFullApprovePerson approvePerson = new ModeFormFullApprovePerson();
            approvePerson.id = GenerateId.getId();
            approvePerson.formFullId = submitData.launchedForm.id;
            approvePerson.state = FormAddProcessFragment.SHEN_PI_STATE_TONG_GUO;
            approvePerson.personId = SPUtils.getInstance().getString("user_id");
            approvePerson.personName = SPUtils.getInstance().getString("user_name");
            approvePerson.processId = writeFormData.formApproveProcessList.get(0).id;
            approvePerson.startTime = TimeUtils.getNowString();
            approvePerson.endTime = TimeUtils.getNowString();
            approvePerson.note = "表单提交人";

            submitData.formFullApprovePerson.add(0,approvePerson);

            //回调执行保存逻辑
            iHandleWriterData.uploadServer(submitData, new IWaitResult() {
                @Override
                public void onResult(String val) {
                    loadingDialog.dismiss();
                    iWaitResult.onResult(val);
                }

                @Override
                public void onError(String error) {
                    loadingDialog.dismiss();
                    iWaitResult.onError(error);
                }
            });

            //删除本地暂存数据
            deleteSqliteData();

        } else {
            loadingDialog.dismiss();
            ToastUtils.showShort("校验失败，请检查表单！");
        }
    }


    private void deleteSqliteData(){
        //删除该表单原数据
        SqliteExcuteCommand.delete(getContext(), ModeFormFile.class,"yiJiId=?",String.valueOf(writeFormData.form.id));
        SqliteExcuteCommand.delete(getContext(), ModeFormOrdinaryFieldData.class,"formId=?",String.valueOf(writeFormData.form.id));
        SqliteExcuteCommand.delete(getContext(), ModeFullForm.class,"formId=?",String.valueOf(writeFormData.form.id));

    }

    /**
     * 暂存
     */
    public void zanCun(){
        LoadingDialog loadingDialog = new LoadingDialog(getContext());
        loadingDialog.showLoading();
        check();
        deleteSqliteData();
        //保存
        List<ModeFormFile> saveSqlImageModeList = loadFormFieldView.getSaveSqlImageModeList();
        for (ModeFormFile formFileMode : saveSqlImageModeList) {
            SqliteExcuteCommand.save(getContext(),formFileMode);
        }

        for (ModeFormOrdinaryFieldData formOrdinaryFieldData : loadFormFieldView.getSaveSqlOrdinaryFieldDataList()) {
            SqliteExcuteCommand.save(getContext(),formOrdinaryFieldData);
        }

        ModeFullForm formData = getFormData();
        SqliteExcuteCommand.save(getContext(),formData);
        loadingDialog.dismiss();
        ToastUtils.showLong("保存完毕！");
    }


    private ModeFullForm getFormData(){
        //表单的信息
        ModeFullForm launchedForm = new ModeFullForm();
        launchedForm.formId = writeFormData.form.id;
        launchedForm.id = writeFormData.id;

        if (writeFormData.form.type == 0) {
            launchedForm.state = 2;
            launchedForm.processEndTime = TimeUtils.getNowString();
        } else if (writeFormData.form.type == 1) {
            launchedForm.state = 1;
        }

        return launchedForm;
    }

    /**
     * 检查表单
     * @return
     */
    private boolean check(){
        if (writeFormData.form.type == 1) {
            return loadFormFieldView.check() && loadFormApproveView.check();
        } else {
            return loadFormFieldView.check();
        }
    }

    private ModeServerSubmitData handlerServerData(){
        ModeServerSubmitData submitData = null;

        if (check()) {
            submitData = new ModeServerSubmitData();

            //表
            submitData.launchedForm = getFormData();

            //文件数据
            submitData.formFullFileData = new ArrayList<>();
            for (ModeFormFile formFileMode : loadFormFieldView.getSaveSqlImageModeList()) {
                //文件地址为空的不保存
                if (StringUtils.isNoEmpty(formFileMode.url)) {
                    ModeFormFullFileData formFullFileData = new ModeFormFullFileData();
                    formFullFileData.reOne = formFileMode.yiJiId;
                    formFullFileData.reTwo = formFileMode.erJiId;
                    formFullFileData.reThree = formFileMode.sanJiId;
                    formFullFileData.dy = FormBuilder.DI_YU;
                    formFullFileData.bucket = FormBuilder.BUCKET_NAME;
                    formFullFileData.rq = 2;
                    formFullFileData.path = formFileMode.url;
                    formFullFileData.orderEx = formFileMode.orderEx;
                    submitData.formFullFileData.add(formFullFileData);
                }
            }

            //普通字段数据
            submitData.formOrdinaryFieldData = new ArrayList<>();
            List<ModeFormOrdinaryFieldData> saveSqlOrdinaryFieldDataList = loadFormFieldView.getSaveSqlOrdinaryFieldDataList();
            for (ModeFormOrdinaryFieldData modeFormOrdinaryFieldData : saveSqlOrdinaryFieldDataList) {
                //字段内容为空的不保存
                if (StringUtils.isNoEmpty(modeFormOrdinaryFieldData.content)) {
                    submitData.formOrdinaryFieldData.add(modeFormOrdinaryFieldData);
                }
            }

            //流程审批人
            submitData.formFullApprovePerson = new ArrayList<>();
            if (writeFormData.formApproveProcessList != null) {
                for (FormApproveProcess formApproveProcess : writeFormData.formApproveProcessList) {
                    if (formApproveProcess.type != FormAddProcessFragment.FA_QI_REN_JIE_DIAN) {
                        if (writeFormData.formApprovePersonMap != null) {
                            List<FormApprovePerson> formApprovePeople = writeFormData.formApprovePersonMap.get(formApproveProcess.id);
                            if (formApprovePeople != null && !formApprovePeople.isEmpty()) {
                                for (FormApprovePerson formApprovePerson : formApprovePeople) {
                                    ModeFormFullApprovePerson formFullApprovePerson = new ModeFormFullApprovePerson();
                                    formFullApprovePerson.id = GenerateId.getId();
                                    formFullApprovePerson.formFullId = writeFormData.id;
                                    formFullApprovePerson.processId = formApproveProcess.id;
                                    formFullApprovePerson.personId = formApprovePerson.personId;
                                    formFullApprovePerson.personName = formApprovePerson.personName;
                                    formFullApprovePerson.state = formApprovePerson.state;
                                    submitData.formFullApprovePerson.add(formFullApprovePerson);
                                }
                            }
                        }
                    }
                }
            }

        }
        return submitData;
    }


    public ViewLoadFormField getLoadFormFieldView() {
        return loadFormFieldView;
    }

    public ModeLoadServerFormConfigData getWriteFormData() {
        return writeFormData;
    }


    public void setWriteFormData(ModeLoadServerFormConfigData writeFormData) {
        this.writeFormData = writeFormData;
    }

    public IHandleWriterData getiHandleWriterData() {
        return iHandleWriterData;
    }

    public void setHandleWriterData(IHandleWriterData iHandleWriterData) {
        this.iHandleWriterData = iHandleWriterData;
    }

    public IWaitResult getiWaitResult() {
        return iWaitResult;
    }

    public void setWaitResult(IWaitResult iWaitResult) {
        this.iWaitResult = iWaitResult;
    }





}
